<template>
  <div>
    <a-steps :current="current" style="width:50%;margin-left:25%;float:left">
      <a-step v-for="item in steps" :key="item.title" :title="item.title" />
    </a-steps>
    <div class="steps-action" style="float:left;margin-left:7%">
      <a-button v-if="current>0" style="margin-left: 8px" @click="prev">
        返回
      </a-button>
      <a-button v-if="current < steps.length - 1" type="primary" @click="next">
        保存并继续设置
      </a-button>
      <a-button v-if="current == steps.length - 1" type="primary" @click="submit">
        提交
      </a-button>
    </div>
    <div class="steps-content" style="display:inline-block">
      <el-row :gutter="100" v-if="current==0" style="margin-top:50px">
        <el-col :xs="9" :sm="9" :md="9" :lg="9" :xl="9">
          <el-card class="box-card" shadow="never">
            <img src="../../../../assets/img/luckDraw/bgImg.png" style="width:100%" alt="">
          </el-card>
        </el-col>
        <el-col :xs="15" :sm="15" :md="15" :lg="15" :xl="15">
          <el-card class="box-card" shadow="never">
            <div>
              <el-form ref="dataForm" :model="rowTemp" label-position="left" label-width="150px" style="width: 900px; margin-left:50px;">
                <el-form-item label="活动期数：">
                  <el-input v-model="rowTemp.name" placeholder="请输入活动期数" size="small" class="fliter-item" style="width:200px"></el-input>
                </el-form-item>
                <el-form-item label="开始日期时间:">
                  <el-date-picker v-model="bgTime" value-format='yyyy-MM-dd HH:mm:ss' type="datetime" placeholder="选择开始日期时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="结束日期时间:">
                  <el-date-picker v-model="overTime" value-format='yyyy-MM-dd HH:mm:ss' type="datetime" placeholder="选择结束日期时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="主办方及规则介绍：">
                  <div>
                    <div ref="editor" style="text-align:left;margin: 5px">

                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="兑奖说明:">
                  <div>
                    <div ref="editor1" style="text-align:left;margin: 5px">
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="100" v-if="current==1" style="margin-top:50px">
        <el-col :xs="9" :sm="9" :md="9" :lg="9" :xl="9">
          <el-card class="box-card" shadow="never">
            <img src="../../../../assets/img/luckDraw/bgImg.png" style="width:100%" alt="">
          </el-card>
        </el-col>
        <el-col :xs="15" :sm="15" :md="15" :lg="15" :xl="15">
          <el-card class="box-card" shadow="never">
            <div>
              <div>
                <el-button size="small" class="filter-item" style="float:right" type="primary" icon="el-icon-edit"
                  @click="handleAdd">
                  添加奖项
                </el-button>
              </div>
              <el-table :data="detailsData" style="margin-top:20px;" border>
                <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
                <el-table-column prop="proInfoName" label="奖品名称" align="center"></el-table-column>
                <el-table-column prop="proMarketPrice" label="市场价格" align="center"></el-table-column>
                <el-table-column label="抵扣小康币" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.xkCoin }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="proInfoNum" label="数量" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="danger" plain size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button type="danger" plain size="small" @click="delProinfo(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-dialog width="60%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="chearData"
                append-to-body>
                <el-form ref="dataForm" :model="tempGoods" label-position="right" label-width="240px" style="width: 700px; margin-left:150px;">
                  <el-form-item label="商品ID(商品查询列表中获取):" prop="proId">
                    <el-input style="width:300px" v-model="tempGoods.proId" />
                    <el-button type="primary" style="margin-left:20px;" @click="queryGoods">查询商品</el-button>
                  </el-form-item>
                  <el-form-item label="商品名称:" v-if="isShow" prop="GoodsName">
                    <el-input v-model="GoodsName" />
                  </el-form-item>
                  <el-form-item label="商品图片：" v-if="isShow">
                    <el-upload
                      class="avatar-uploader"
                      action="http://10.0.0.123:10001/uploadImgUrl"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :http-request="customRequest">
                      <img style="width:100px;height:100px" v-if="tempGoods.imageUrl" :src="tempGoods.imageUrl" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="商品规格(不同价格)：" v-if="isShow" prop="proType">
                    <el-table :data="data1List" tooltip-effect="dark" ref="tableData" @row-click="singleElection"
                      stripe border style="width:100%">
                      <el-table-column prop="prop" label="单选" align="center">
                        <template slot-scope="scope">
                          <el-radio class="radio" v-model="templateSelection" :label="scope.$index">&nbsp;</el-radio>
                        </template>
                        <!-- v-model="scope.row.id == transferForm.selectedId" -->
                      </el-table-column>
                      <el-table-column label="型号" align="center">
                        <template slot-scope="scope">
                          <span>{{scope.row.proTitle}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="销售价格" align="center">
                        <template slot-scope="scope">
                          <span>{{scope.row.proSellPrice/100}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="采购价格" align="center">
                        <template slot-scope="scope">
                          <span>{{scope.row.purchansePrice/100}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="市场价格" align="center">
                        <template slot-scope="scope">
                          <span>{{scope.row.proMarketPrice/100}}</span>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                  <el-form-item label="商品数量：" prop="remake">
                    <el-input v-model="tempGoods.proInfoNum" />
                  </el-form-item>
                  <el-form-item label="抵扣小康币：" prop="helpMoney">
                    <el-input v-model="tempGoods.xkCoin" />
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="dialogFormVisible = false">取 消</el-button>
                  <el-button type="primary" @click="dialogStatus === 'create' ? createCommodity() : updateCommodity()">
                    确定
                  </el-button>
                </div>
              </el-dialog>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="100" v-if="current==2" style="margin-top:50px">
        <el-col :xs="9" :sm="9" :md="9" :lg="9" :xl="9">
          <el-card class="box-card" shadow="never">
            <img src="../../../../assets/img/luckDraw/bgImg.png" style="width:100%" alt="">
          </el-card>
        </el-col>
        <el-col :xs="15" :sm="15" :md="15" :lg="15" :xl="15">
          <el-card class="box-card" shadow="never">
            <div>
              <el-form ref="dataForm" label-position="left" label-width="150px" style="width: 900px; margin-left:50px;">
                <el-form-item label="活动期数：">
                  <el-radio-group v-model="rowTemp.type">
                    <el-radio-button label="1">扣减小康币</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="中奖名单：">
                  <el-radio-group v-model="rowTemp.status">
                    <el-radio-button :label="0">关闭</el-radio-button>
                    <el-radio-button :label="1">开启</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  import {
    mapGetters
  } from 'vuex'
  import {
    getDetails,
    delProinfo,
    updateGoods,
    isAdd,
    settings
  } from "@/api/luckDraw/index";
  import {
    queryGoods
  } from '@/api/activityManage'
  import {addImg} from '@/api/headWheel'
  import E from 'wangeditor'
  import {
    parseTime,
    formatDate
  } from "@/utils/index";
  import {
    getToken
  } from '@/utils/auth'
  // import { add, edit } from '@/api/dict'
  export default {
    inject: ["reload"],
    data() {
      return {
        headers: {
          'Authorization': 'Bearer ' + getToken()
        },
        value1: '',
        templateSelection: '',
        current: 0,
        data1List: [],
        detailsData: [],
        dialogFormVisible: false,
        isShow: false,
        dialogStatus: '',
        GoodsName: '',
        textMap: {
          update: '编辑',
          create: '添加'
        },
        delId: '',
        tempGoods: {
          proMarketPrice: '',
          proTitle: '',
          proPriceId: '',
          weekPrizeId: '',
          proInfoId: '',
        },
        newRowTemp: {},
        editor: '',
        editor1: "",
        steps: [{
          title: '基本设置',
        }, {
          title: '奖品设置',
        }, {
          title: '高级设置',
        }],
        goodsData: '', //根据商品id查询的数据
      }
    },
    props: {
      rowId: {
        type: String,
        required: true
      },
      changeShow: {
        type: Boolean,
        required: true
      },
      rowTemp: {
        type: Object,
        // required:true
      },
      overTime: {
        type: String,
        required: true
      },
      bgTime: {
        type: String,
        required: true
      }
    },
    computed: {
      ...mapGetters([
        'imagesUploadApi'
      ])
    },
    mounted() {
      //主办方及规则介绍
      this.editor = new E(this.$refs.editor)
      this.editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
      // 不可修改
      this.editor.customConfig.uploadImgHeaders = this.headers
      // 自定义文件名，不可修改，修改后会上传失败
      this.editor.customConfig.uploadFileName = 'file'
      this.editor.customConfig.uploadImgServer = this.imagesUploadApi // 上传图片到服务器
      this.editor.customConfig.onchange = (html) => {
        this.rowTemp.activityRules = html
      }
      this.editor.create()
      //兑奖说明
      this.editor1 = new E(this.$refs.editor1)
      this.editor1.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
      // 不可修改
      this.editor1.customConfig.uploadImgHeaders = this.headers
      // 自定义文件名，不可修改，修改后会上传失败
      this.editor1.customConfig.uploadFileName = 'file'
      this.editor1.customConfig.uploadImgServer = this.imagesUploadApi // 上传图片到服务器
      this.editor1.customConfig.onchange = (html) => {
        this.rowTemp.description = html
      }
      this.editor1.create()
    },
    methods: {
      //时间戳转日期格式
      parseTime,
      getItemList(rowTemp) {
        console.log(rowTemp)
        this.editor.txt.html('<p>' + rowTemp.activityRules + '</p>')
        this.editor1.txt.html('<p>' + rowTemp.description + '</p>')
      },
      next() {
        this.current++
        if (this.current === 1) {
          this.findDetail()
        }
      },
      prev() {
        this.current--
        if (this.current === 1) {
          this.findDetail()
        }
      },
      handleAvatarSuccess(res, file) {
          this.tempGoods.imageUrl = URL.createObjectURL(file.raw);
      },
      customRequest (data) {
        const formData = new FormData()
        formData.append('file', data.file)
        this.saveFile(formData)
      },
      saveFile (formData) {
        addImg(formData).then(res=>{
          // this.imageUrl=res.data
          this.$set(this.tempGoods, "imageUrl", res.data.filePath);
        })
      },
      //奖品设置
      findDetail() {
        console.log(this.rowId)
        this.showDetailDialog = true;
        var params = {
          id: this.rowId,
        }
        getDetails(params).then(res => {
          this.detailsData = res.data.content;
        })
      },
      //删除奖品
      delProinfo(row) {
        this.delId = row.id
        var ids = []
        ids.push(this.delId)
        var params = {
          ids: ids
        }
        delProinfo(params).then(res => {
          if (res.code === '200') {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.findDetail()
          }
        })
      },
      //编辑
      chearData() {
        this.isShow = false
      },
      singleElection(row) {
        this.templateSelection = this.data1List.indexOf(row);
        console.log(this.templateSelection)
        this.tempGoods.proMarketPrice = row.proMarketPrice
        this.tempGoods.proInfoName = row.proTitle
        this.tempGoods.proPriceId = row.proPriceId
      },
      queryGoods() {
        queryGoods(this.tempGoods.proId).then(res => {
          this.goodsData = res.data
          this.GoodsName = res.data.infoName
          this.tempGoods.proInfoId = res.data.proInfoId
          this.tempGoods.imageUrl = res.data.imageUrl
          this.data1List = res.data.list
          console.log(this.data1List)
          if (this.data1List.length === 0) {
            this.isShow = false
          } else {
            this.isShow = true
          }
          this.templateSelection = null
          this.tempGoods.proPriceId = ''
          // this.rowId=''
        })

      },
      handleUpdate(row) {
        this.tempGoods = Object.assign({}, row)
        console.log(this.tempGoods)
        // this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.queryGoods()
        this.isShow = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      restGoods() {
        this.tempGoods = {}
      },
      handleAdd() {
        this.restGoods()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()
        // })
      },
      createCommodity() {
        this.tempGoods.weekPrizeId = this.rowId
        this.tempGoods.proInfoName = this.GoodsName
        this.tempGoods.imageUrl = this.goodsData.imageUrl
        isAdd(this.tempGoods).then(res => {
          if (res.code === '200') {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          }
          this.dialogFormVisible = false
          this.findDetail()
        })
      },
      updateCommodity() {
        this.tempGoods.weekPrizeId = this.rowId
        this.tempGoods.proInfoName = this.GoodsName
        updateGoods(this.tempGoods).then((res) => {
          // this.dialogFormVisible = false
          if(res.code==='200'){
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
            this.findDetail()
          }
        })
      },
      //提交表单
      submit() {
        this.rowTemp = {
          id: this.rowTemp.id,
          name: this.rowTemp.name,
          startTime: new Date(this.bgTime).getTime(),
          endTime: new Date(this.overTime).getTime(),
          activityRules: this.rowTemp.activityRules,
          description: this.rowTemp.description,
          isShowWinningList: this.rowTemp.status,
          type: this.rowTemp.type
        }
        settings(this.rowTemp).then(res => {
          if (res.code === '200') {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.reload()
          } else {
            this.$notify({
              title: '失败',
              message: '修改失败',
              type: 'danger',
              duration: 2000
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
  .editor-content {
    padding-left: 5px;
  }
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>